<?php
namespace Backend\Controllers\Car;

use Backend\Controllers\BaseController;
use Backend\Libraries\Helper;
use Backend\Models\Car\Kulala;
use Commons\Http;
use Commons\MobileControl\Car;

/**
 * @RoutePrefix("/car/kulala")
 */
class KulalaController extends BaseController
{
    public function initialize()
    {
        parent::initialize();
    }

    /**
     * @Post(
     *     "/gets"
     * )
     */
    public function getsAction()
    {
        $data = [
            'page' => $this->request->getPost('page'),
            'size' => $this->request->getPost('pageSize')
        ];
        if ($data['page'] == '' || !is_numeric($data['page'])) {
            return $this->json(['code' => 500, 'msg' => '未获取到当前的页数！']);
        }
        if ($data['size'] == '' || !is_numeric($data['size'])) {
            return $this->json(['code' => 500, 'msg' => '未获取到当前的每页的条数！']);
        }
        $data['size'] = intval($data['size']);
        $data['page'] = intval($data['page']);
        $offset       = intval(($data['page'] - 1) * $data['size']);
        $model        = new Kulala();
        $list         = $model->gets($data['size'], $offset);
        if ($list !== false) {
            return $this->json([
                'code' => 200,
                'msg'  => '获取成功!',
                'list' => $list
            ]);
        }
        return $this->json([
            'code' => 500,
            'msg'  => '获取失败，系统错误~'
        ]);
    }

    /**
     * @Post(
     *     "/getCount"
     * )
     */
    public function getCountAction()
    {
        $cnt = (new Kulala())->getCount();
        if ($cnt === false) {
            return $this->json([
                'code' => 500,
                'msg'  => '获取失败，系统错误~'
            ]);
        }
        return $this->json([
            'code'  => 200,
            'count' => $cnt
        ]);
    }

    /**
     * @Post(
     *     "/get"
     * )
     */
    public function getAction()
    {
        $id    = $this->request->getPost('id');
        $model = new Kulala();
        $ret   = $model->get($id);
        $res   = (new Car())->query(['carId' => $ret['kc_id']], 'kulala.api.car.status.get');
        if (isset($res['result'])) {
            $path                        = array_reverse(explode(',', $res['carStatusInfo']['gps']));
            $gps                         = Helper::gpsToBaiDuMap([implode(',', $path)]);
            $gps                         = [
                'lng' => $gps['result'][0]['x'],
                'lat' => $gps['result'][0]['y']
            ];
            $res['carStatusInfo']['gps'] = $gps;
            return $this->json(['code' => 200, 'msg' => '获取成功', 'list' => $res['carStatusInfo']]);
        }
    }
}
